package com.awesumgames.awesum;

import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.egl.EGLConfig;

import com.awesumgames.awesum.AwesumGlobal.Awesum;

import tv.ouya.console.api.OuyaController;
import android.opengl.GLSurfaceView;
import android.os.SystemClock;
//import android.util.Log;

public class AwesumRenderer implements GLSurfaceView.Renderer {
    //static public GameRenderer s_instance = null;
    //private float _width = 1920;
    //private float _height = 1080;
    private long _prevTime = 0;
    
	public AwesumRenderer() {
	}

	public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
		//Awesum.debug("renderer onSurfaceCreated start");
        synchronized (Game.lock) {
			Game.setup();
        }
		//Awesum.debug("renderer onSurfaceCreated end");
	}

	public void onSurfaceChanged(GL10 glUnused, int w, int h) {
		//synchronized (Game.lock) {
			//Awesum.debug("renderer w h set");
			Game.updateScreen(w, h);
		//}
	}

	public void onDrawFrame(GL10 glUnused) {
		long time = SystemClock.uptimeMillis() % 10000L;
		if (_prevTime == 0)
			step(1);
		else {
			long diff = time - _prevTime;
			if (diff >= Game.timeStep * 1000f) {
				step((float)diff / 1000f);
				//Log.d("debug", "between steps = " + Long.toString(diff));
			}
		}
		_prevTime = time;
		
		synchronized (Game.lock) {
			Game.draw();
		}
	}
	
	private void step(float seconds) {
		synchronized (Game.pauseInput) {
            Game.step(seconds);
            OuyaController.startOfFrame();
        }
	}
	
}
